import { authorities, getUserByToken } from '@/api/login'
import { loginOut } from '../../api/logOut'
import { getToken, getUser, removeToken, removeUser, setToken, setUser, setRetails } from '../../utils/localStore'
import { constantRoutes } from '@/router'
import { editList, userLoginFun } from '@/utils/loginIndex'
import { encrypt } from '@/utils/aesEdit'
import { GetQueryValue, toPortal } from '@/api/SignUtil'
import { Message } from 'element-ui'
import router from '@/router'
// import store from '@/store'

const user = {
  state: {
    user: getUser(),
    token: getToken(),
    name: '',
    userName: '',
    avatar: '',
    storeId: -1,
    userId: 0,
    storeName: '',
    roles: [],
    rolesTable: [],
    routes: [],
    addRoutes: [],
    position: -1,
    positionRoles: [],
    areaList: [],
    storeNameList: [],
    appList: ['A000017'],
    appIdLogin: 'A000017'
  },

  mutations: {
    SET_USER: (state, user) => {
      state.user = user
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_User_Name: (state, userName) => {
      state.userName = userName
    },
    SET_Mobile: (state, mobile) => {
      state.mobile = mobile
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_STORE_ID: (state, storeId) => {
      state.storeId = parseInt(storeId)
    },
    SET_USER_ID: (state, userId) => {
      state.userId = userId
    },
    SET_STORE_NAME: (state, storeName) => {
      state.storeName = storeName
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_ROLES_TABLE: (state, rolesTable) => {
      state.rolesTable = rolesTable
    },
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      // state.routes = constantRoutes.concat(routes)
      state.routes = routes
    },
    SET_AREA_LIST: (state, areaList) => {
      state.areaList = areaList
    },
    SET_STORENAME_LIST: (state, storeList) => {
      state.storeNameList = storeList
    }
  },

  actions: {
    // user-center login
    userLogin({ commit }, userInfo) {
      const appId = user.state.appIdLogin
      const param = {
        password: encrypt(userInfo.password.trim()),
        userId: userInfo.username.trim(),
        appId: appId,
        url: ''
      }
      return new Promise((resolve, reject) => {
        userLoginFun(param).then(res => {
          const data = res
          data.userName = data.userId
          setRetails('')
          setUser(data)
          commit('SET_USER', data)
          setToken(data.token)
          commit('SET_TOKEN', data.token)
          commit('SET_USER_ID', data.userId)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // portal中通过token登录
    loginByToken({ commit }, token) {
      setToken(token)
      commit('SET_TOKEN', token)
      return new Promise((resolve, reject) => {
        getUserByToken({ 'token': token }).then(res => {
          const data = res.result
          data.userName = data.userId
          setRetails(GetQueryValue('retails'))
          setUser(data)
          commit('SET_USER', data)
          commit('SET_USER_ID', data.userId)
          commit('SET_THE_ID', data.id)
          commit('SET_User_Name', data.userId)
          resolve()
        }).catch(err => {
          reject(err)
        })
      })
    },

    // 权限设置
    findAuthorities({ commit }) {
      const data = getUser()
      // console.log(JSON.stringify(data))
      data.nickName = data.nickName ? data.nickName : data.name
      const param3 = {
        appIds: user.state.appList,
        userId: data.userId
      }
      commit('SET_USER_ID', data.userId)
      return new Promise((resolve, reject) => {
        console.log('window.appName:' + window.appName)
        authorities(param3).then(res => {
          const data2 = res.result

          data.ruleList = editList(data2)

          if (data.ruleList && data.ruleList.length > 0) {
            const admin103List = data.ruleList
            if (admin103List.length > 0) {
              commit('SET_ROLES', data.ruleList)
              data.scopeMap = data2.scopeMap
              commit('SET_NAME', data.nickName)
              commit('SET_User_Name', data.userId)
              commit('SET_USER', data)
              findByStoreIdStoreList(data).then(res => {
                resolve()
              })
            } else {
              Message({
                showClose: true,
                message: '您没有权限无法登陆',
                type: 'warning'
              })
              removeUser()
              removeToken()
              window.setTimeout(() => {
                router.go(-1)
              }, 2000)
              return
            }
          } else {
            Message({
              showClose: true,
              message: '您没有权限无法登陆',
              type: 'warning'
            })
            removeUser()
            removeToken()
            window.setTimeout(() => {
              router.go(-1)
            }, 2000)
            return
          }
        }).catch(e => {
          reject(e)
        })
      })
    },

    generateRoutes({ commit }, roles) {
      return new Promise(resolve => {
        const accessedRoutes = filterAsyncRoutes(constantRoutes, roles)
        commit('SET_ROLES_TABLE', roles)
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      })
    },

    // new 根据token登出
    // loginOut({commit}) {
    LogOut({ commit }) {
      return new Promise((resolve, reject) => {
        const data = getUser()
        const token = getToken()
        if (data && token) {
          const param = {
            token: token
          }
          loginOut(param).then(res => {
            commit('SET_USER', '')
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            commit('SET_ROLES_TABLE', [])
            commit('SET_STORE_ID', -1)
            commit('SET_USER_ID', 0)
            commit('SET_STORE_NAME', '')
            commit('SET_AREA_LIST', [])
            removeUser()
            removeToken()
            toPortal()
            resolve()
          })
        } else {
          removeUser()
          removeToken()
          toPortal()
        }
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_USER', '')
        commit('SET_User_Name', '')
        commit('SET_Mobile', '')
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_ROLES_TABLE', [])
        commit('SET_STORE_ID', -1)
        commit('SET_USER_ID', 0)
        commit('SET_STORE_NAME', '')
        commit('SET_AREA_LIST', [])
        removeUser()
        removeToken()
        toPortal()
        resolve()
      })
    }
  }
}

export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  return res
}

function hasPermission(roles, route) {
  if (route.meta && (route.meta.roles || route.meta.exclude_roles)) {
    if (!route.meta.exclude_roles) {
      return roles.some(role => route.meta.roles.includes(role))
    } else {
      if (route.meta.roles) {
        return roles.some(role => route.meta.roles.includes(role)) && !roles.some(role => route.meta.exclude_roles.includes(role))
      } else {
        return !roles.some(role => route.meta.exclude_roles.includes(role))
      }
    }
  } else {
    return true
  }
}

// 门店列表范围
function findByStoreIdStoreList(data) {
  return new Promise((resolve, reject) => {
    const scope = data.scopeMap
    if (scope && Object.keys(scope).length !== 0) {
      // if (scope[3]) {
      //   scope[3] = scope[3].filter(e => !isNaN(e) && e)
      // }
      // if (scope[3] && scope[3].length > 0) {
      //   data.storeId = scope[3][0] ? parseInt(scope[3][0]) : ''
      //   setUser(data)
      //   store.commit('SET_STORE_ID', scope[3][0] || '')
      //   // const query = {
      //   //   storeId: [...scope[3] || '', ...scope[4] || ''],
      //   //   storeStatus: []
      //   // }
      //   resolve()
      // } else {
      //   Message({
      //     showClose: true,
      //     message: '没有所属店铺',
      //     type: 'warning'
      //   })
      //   removeUser()
      //   removeToken()
      //   return
      // }
      resolve()
    } else {
      resolve()
    }
  })
}

export default user
